<template>
	<div class="content">
		<div class="pageSearchView">
			<SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />
		</div>

		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					计划信息
				</div>
				<div class="pageTableButView">
					<el-button @click="handleAdd" type="primary">新建</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 350px)"
								:expand-row-keys="expandedRows" :loading="isLoading" row-key="id" @expand-change="handleExpandChange">
				<el-table-column type="expand">
					<template #default="props">
						<div m="4">

							<el-table ref="tableCil" border size="small" :data="props.row.children">
								<el-table-column type="index" width="50" label="序号" align="center" />
								<el-table-column label="产品名称" prop="productId" min-width="150" align="center" show-overflow-tooltip>
									<template #default="scope">
                    <span>{{
												productData.find((i) => i.id === scope.row.productId)
													?.productName
											}}</span>
									</template>
								</el-table-column>
								<el-table-column label="工艺路线名称" prop="processRouteId" min-width="150" align="center"
																 show-overflow-tooltip>
									<template #default="scope">
                    <span>{{
												allRouteData.find(
													(i) => i.id === scope.row.processRouteId
												)?.processName
											}}</span>
									</template>
								</el-table-column>
								<el-table-column label="物料名称" prop="bomId" align="center" show-overflow-tooltip>
									<template #default="scope">
                    <span>{{
												materialData.find((i) => i.id === scope.row.bomId)?.materialBomName
											}}</span>
									</template>
								</el-table-column>
								<el-table-column label="数量" prop="planCount" min-width="150" align="center" show-overflow-tooltip />
								<el-table-column label="操作" prop="ops" min-width="100" align="center" fixed="right">
									<template #default="scope">
										<el-button type="text" size="small" :icon="Download" :disabled="scope.row.status === 1"
															 @click="handleIssue(scope.row, props.row)">下发
										</el-button>

									</template>
								</el-table-column>
							</el-table>
						</div>
					</template>
				</el-table-column>

				<el-table-column label="序号" align="center" width="70">
					<template #default="scope">
						{{ (current - 1) * pageSize + scope.$index + 1 }}
					</template>
				</el-table-column>
				<el-table-column prop="planNo" label="计划号" width="150" />
				<el-table-column prop="planBeginTime" label="计划开始时间" width="180" />
				<el-table-column prop="planEndTime" label="计划结束时间" width="180" />
				<el-table-column prop="organizationId" label="工厂/车间" width="150">
					<template #default="scope">

            <span>{{
								lineListAll.find(
									(i) => i.id === scope.row.organizationId
								)?.orgName
							}}</span>
					</template>
				</el-table-column>


				<el-table-column prop="status" label="计划状态" width="100">
					<template #default="scope">
						{{ scope.row.status === 0 ? '未完成' : '已完成' }}
					</template>
				</el-table-column>
				<el-table-column prop="type" label="计划类型" width="100">
					<template #default="scope">
						{{ getTypeName(scope.row.type) }}
					</template>
				</el-table-column>
				<el-table-column prop="actualBeginTime" label="实际开始时间" width="180" />
				<el-table-column prop="actualEndTime" label="实际结束时间" width="180" />

				<el-table-column label="操作" width="200" fixed="right">
					<template #default="scope">

						<el-button type="text" size="small" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
						<el-button type="danger" plain text size="small" @click="handleDel(scope.row)"
											 :disabled="scope.row.status === 1" :icon="Delete">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background layout="prev, pager, next" :total="pageTotal" :page-size="pageSize"
											 :current-page="current" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>

		<!-- 编辑/新建弹框 -->
		<el-dialog v-model="showCrud" title="计划信息" width="50%">
			<el-form :model="formData" label-width="100px" label-position="top">
				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="计划开始时间-计划结束时间" required>
							<el-date-picker v-model="formData.planBeginTime" type="datetimerange" valueFormat="YYYY-MM-DD HH:mm:ss"
															range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="工厂/车间" required>
							<el-tree-select v-model="formData.organizationId" :render-after-expand="false" :data="lineGroup"
															clearable />
						</el-form-item>
					</el-col>

				</el-row>

				<el-row :gutter="16">
					<el-col :span="12">
						<el-form-item label="计划类型" required>
							<el-select v-model="formData.type" placeholder="请输入计划类型">
								<el-option v-for="item in typeData" :key="item.value" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<template v-for="(item, index) in formData.keys" :key="index">
					<el-row :gutter="16">
						<el-col :span="12">
							<el-form-item :label="`产品名称`">
								<el-select v-model="item.productId" placeholder="请选择产品名称" @change="e => changeProduct(e, index, item)">
									<el-option v-for="i in productData" :key="i.id" :value="i.id" :label="i.productName" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="`路线名称`">
								<el-select v-model="item.processRouteId" placeholder="请选择路线名称">
									<el-option v-for="i in item.allRouteData" :key="i.id" :value="i.id" :label="i.processName" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="16">
						<el-col :span="12">
							<el-form-item :label="`物料bom名称`">
								<el-select v-model="item.bomId" placeholder="请选择物料bom名称">
									<el-option v-for="i in item.materialBom" :key="i.id" :value="i.id" :label="i.materialBomName" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="`下发数量`">
								<el-input-number v-model="item.planCount" placeholder="请输入下发数量" style="width: 100%" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24" :offset="22">
							<el-button type="primary" :icon="CircleClose" size="small" @click="handleRemove(index)">

							</el-button>
						</el-col>
					</el-row>
				</template>

				<div style="width: 100%; display: flex; justify-content: center;">
					<el-button type="dashed" block @click="handleAddItem" :icon="CirclePlus"> 添加产品</el-button>
				</div>

			</el-form>
			<template #footer>
        <span class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :disabled="formData.status === 1">保存</el-button>
        </span>
			</template>
		</el-dialog>
		<DialogComponent ref="dialogRef" />
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBaseDataPlanData } from '@/hooks/production/productionPlan';
import SearchForm from '@/components/SearchForm.vue';
import { ProductionPlanDetailApi, productBaseDataPlanApi } from '@/api/production/productionPlan';
import { CircleClose, CirclePlus, Delete, Edit, Download } from '@element-plus/icons-vue';


const {
	searchParam,
	pageSize,
	current,
	pageTotal,
	paginatedData,
	searchFields,
	productData,
	allRouteData,
	materialData,
	lineListAll,
	typeData,
	lineGroup,
	handleAddSubmit,
	handleSearch,
	handleSizeChange,
	handleCurrentChange,
	addBaseDataPlan,
	deleteBaseDataPlan,
	handleIssue,
	isLoading
} = useBaseDataPlanData();
const index = ref(0);
const expandedRows = ref([]); // 用于跟踪哪些行是展开的
const formData = ref({
	planNo: '',
	name: '',
	planBeginTime: null,
	planEndTime: null,
	actualBeginTime: null,
	actualEndTime: null,
	organizationId: '',
	status: '0',
	type: '0',
	keys: [
		{
			productId: '',
			allRouteData: '',
			materialBom: '',
			index: index.value,
			status: 1
		}
	]
});
const handleRemove = (index) => {
	formData.value.keys.splice(index, 1);
};
const handleAddItem = () => {

	index.value++;
	if (formData.value.keys) {
		formData.value.keys.push({
			value: '',
			index: index.value,
			status: 1
		});
	} else {
		formData.value = {
			...formData.value,
			keys: [
				{
					productId: '',
					allRouteData: '',
					materialBom: '',
					index: index.value,
					status: 1
				}
			]
		};
	}
};
const changeProduct = (e: string, index: number) => {
	keysArray(e, index);
};
const keysArray = (e: string, index: number) => {
	console.log(e, 'eeeee');
	const filteredAllRouteData = allRouteData.value.filter((i) => i.productId === e);
	const filteredMaterialBom = materialData.value.filter((i) => i.productId === e);
	formData.value.keys[index] = {
		...formData.value.keys[index],
		productId: e,
		allRouteData: filteredAllRouteData,
		materialBom: filteredMaterialBom
	};

};
const getTypeName = (type: string) => {
	const name = typeList.value.find((item: any) => item.value === type);
	return name ? name.label : '';
};

const typeList = ref([
	{ label: '未完成', value: '0' },
	{ label: '已完成', value: '1' }
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

// 新建记录
const handleAdd = () => {
	isEdit.value = false;
	formData.value = {};
	showCrud.value = true;
};

// 编辑记录
const handleEdit = (row: any) => {
	isEdit.value = true;
	ProductionPlanDetailApi({ planId: row.id }).then((res) => {

		formData.value = {
			...row,
			planBeginTime: [row.planBeginTime, row.planEndTime],
			keys: res.data.records
		};
		res.data.records.map((item: any, index: number) => {
			console.log(row, '(row', keysArray(item.productId, index));
			return keysArray(item.productId, index);
		});
	});

	showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		await deleteBaseDataPlan(row.id);
	}).catch(() => {
	});
};

// 保存记录
const handleSave = async () => {
	handleAddSubmit(formData.value, (() => {
		showCrud.value = false;
	}));
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row, expanded) => {
	if (expanded) {
		rowChildren(row);
		expandedRows.value.push(row.id);
	} else {
		const index = expandedRows.value.indexOf(row.id);
		if (index > -1) {
			expandedRows.value.splice(index, 1);
		}
	}

	// else {
	//   getList();
	// }
};

function collapseAll() {
	expandedRows.value = [];
}

const rowChildren = (row: any) => {
	ProductionPlanDetailApi({ planId: row.id }).then((res) => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		const listGroup = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data.records };
			}
			return item;
		});
		paginatedData.value = listGroup;
	});
};

// 获取列表
const getList = async () => {
	try {
		const response = await productBaseDataPlanApi({
			...searchParam.value,
			current: current.value,
			pageSize: pageSize.value
		});
		if (response.code === 200) {
			paginatedData.value = response.data.records.map((item) => ({
				...item,
				children: [],
				layer: 1,
				_loading: false
			}));
			pageTotal.value = response.data.total;
			collapseAll();
		} else {
			ElMessage.warning(response.message);

		}
	} catch (error) {
		ElMessage.error('获取列表失败');
	}
	isLoading.value = false;
};

onMounted(() => {
	getList();
});
</script>

<style scoped></style>
